package com.yyfax.infrastructure.upgrade;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.Constants;
import com.yyfax.infrastructure.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by HenryZhang on 2016/12/28.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class DownloadService extends IntentService {
	private static final String TAG = "DownloadService";

	private static final int NOTIFICATION_ID = 0;
	private static final int BUFFER_SIZE = 10 * 1024;// 8k ~ 32K

	private NotificationManager mNotifyManager;
	private NotificationCompat.Builder mBuilder;

	private String mApplicationID;

	public DownloadService() {
		super(TAG);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		mBuilder = new NotificationCompat.Builder(this);

		String appName = getString(getApplicationInfo().labelRes);
		int icon = getApplicationInfo().icon;
		mBuilder.setContentTitle(appName).setSmallIcon(icon);

		InputStream in = null;
		FileOutputStream out = null;
		try {
			String urlStr = intent.getStringExtra(Constants.APK_DOWNLOAD_URL);
			mApplicationID = intent.getStringExtra(Constants.APPLICATION_ID);
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setDoOutput(false);
			conn.setConnectTimeout(10 * 1000);
			conn.setReadTimeout(10 * 1000);
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
			conn.connect();

			long byteTotal = conn.getContentLength();
			long byteSum = 0;
			int byteRead;

			in = conn.getInputStream();

			File dir = StorageUtils.getCacheDirectory(this);
			String apkName = urlStr.substring(urlStr.lastIndexOf("/") + 1, urlStr.length());
			File apkFile = new File(dir, apkName);
			out = new FileOutputStream(apkFile);
			byte[] buffer = new byte[BUFFER_SIZE];
			int oldProgress = 0;

			while ((byteRead = in.read(buffer)) != -1) {
				byteSum += byteRead;
				out.write(buffer, 0, byteRead);

				int progress = (int) (byteSum * 100L / byteTotal);
				if (progress != oldProgress) {//下载过程中没进度不更新
					updateProgress(progress);
				}
				oldProgress = progress;
			}

			installAPk(apkFile);
//			mNotifyManager.cancel(NOTIFICATION_ID);
		} catch (Exception e) {
			CLog.e(TAG, "download apk file error");
		} finally {
			CLog.i(TAG, "doing finally");
			if (out != null) {
				try {
					out.close();
				} catch (IOException ignored) {
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException ignored) {
				}
			}
		}
	}

	private void updateProgress(int progress) {
		mBuilder.setContentText(getString(R.string.update_download_progress, progress)).setProgress(100, progress, false);
		PendingIntent intent = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);
		mBuilder.setContentIntent(intent);//如果不setContentIntent，4.0以下会异常
		mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
	}

	/**
	 * http://www.jayfeng.com/2016/11/09/%E4%BD%BF%E7%94%A8FileProvider/
	 * http://jk2k.com/2016/01/install-apk-automatically-after-the-download-is-complete-with-download-manager/
	 * http://www.jianshu.com/p/1489fcbd2401
	 */
	private void installAPk(File apkFile) {
		if (!apkFile.exists()) {
			Toast.makeText(this, "下载失败", Toast.LENGTH_SHORT).show();
			return;
		}

		Uri uri = Uri.fromFile(apkFile);
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_VIEW);
		String mimeType = getMIMEType(apkFile);
		if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
			intent.addCategory(Intent.CATEGORY_DEFAULT);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setType(mimeType);
			intent.setData(uri);
			intent.setDataAndType(uri, mimeType);
		} else {
			intent.addFlags(268435456);//可能不需要
			intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			Uri contentUri = FileProvider.getUriForFile(this, mApplicationID + ".fileProvider", apkFile);
			intent.setDataAndType(contentUri, mimeType);
		}

		try {
			startActivity(intent);
		} catch (Exception e) {
			Toast.makeText(this, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
		}
	}

	public String getMIMEType(File file) {
		String type;
		String fileName = file.getName();
		String lowerCaseName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
		type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(lowerCaseName);
		return type;
	}
}
